const express=require("express");
const app=express()

const got = require('got');
var fs = require("fs")

const config=require("./config.js");
let {appid,appsecret,filePath}=config;
// console.log(config)

class Token {
	constructor(appid,appsecret){
		this.appid=appid;
		this.appsecret=appsecret;
		this.filePath=filePath;
		// this.init()
	}

	//初始化
	async init(){
		var result =this.get();
		// console.log(result,"3333")
		if(!result){


			var result =await this.create()
			// console.log(result)
		}
		// console.log(result)
		return result;
		
	}
	/*
		创建新的access_token
		@return 返回token
	*/
	async create(){
		var url=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.appid}&secret=${this.appsecret}`
		// console.log(url,"1111")

		const response = await got(url);
		// console.log(response.body)
		var obj=JSON.parse(response.body);
		obj.addtime=new Date().getTime();
		// // console.log(obj,"4444")
		// console.log(JSON.stringify(obj),"66666")
		fs.writeFileSync(this.filePath,JSON.stringify(obj));
		return obj.access_token;
	}

	/*
		读取access_token
		@return 如果过期返回false；否则返回返回token
	*/
	get(){
		//打开本地文件，检测token是否过期
		const content=fs.readFileSync(this.filePath)

		var obj=JSON.parse(content);
		var nowtime=new Date().getTime()
		// console.log(obj)

		if(nowtime>=obj.addtime+7200*1000){
			return false;
		}
		// console.log(obj)
		return obj.access_token;
	}

}

var model=new Token(appid,appsecret)
var token=model.init();
// console.log(token,"4444");
module.exports=token;


